<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">用户登录</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginForm" label-width="0" class="login-form">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" prefix-icon="el-icon-user" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="loginForm.password" prefix-icon="el-icon-lock" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')" class="login-button">登录</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm('loginForm')" class="reset-button">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from '@/services/api'

export default {
  name: 'UserLogin',
  data() {
    return {
      loginForm: {
        username: 'wangsong',
        password: 'wangsong'
      },
      rules: {
        username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            const response = await axios.post('/login', this.loginForm)
            if (response.data.result === 'success') {
              this.$store.dispatch('login', response.data.data)
              await this.$store.dispatch('fetchPermissions')

              this.$router.push('/')
            } else {
              this.$message.error(response.data.data)
            }
          } catch (error) {
            console.error('登录错误:', error)
            this.$message.error('登录失败')
          }
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.login-card {
  width: 350px;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  color: #409EFF;
}

.login-form {
  padding: 20px;
}

.login-button, .reset-button {
  width: 100%;
}

.login-button {
  margin-bottom: 10px;
}
</style>